package com.maingel.showcase.ui;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.maingel.showcase.R;
import com.maingel.showcase.entity.User;
import com.maingel.showcase.service.ILoginService;

import javax.inject.Inject;

import retrofit.RetrofitError;
import roboguice.inject.ContentView;
import roboguice.inject.InjectView;
import roboguice.util.RoboAsyncTask;

@ContentView(R.layout.activity_login)
public class LoginActivity extends BaseActivity {
    @InjectView(R.id.login_username)
    private EditText usernameEditText;
    @InjectView(R.id.login_password)
    private EditText passwordEditText;
    @InjectView(R.id.login_submit)
    private Button loginButton;

    @Inject
    private ILoginService loginService;

    private RoboAsyncTask<Boolean> loginTask;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                login();
            }
        });
    }

    private void login() {
        if(loginTask != null){
            return;
        }
        loginTask = new RoboAsyncTask<Boolean>(LoginActivity.this) {
            private User user;

            @Override
            public Boolean call() throws Exception {
                Log.v("call: ", Thread.currentThread().getName());
                user = loginService.login(
                        usernameEditText.getText().toString(), passwordEditText.getText().toString());
                return true;
            }

            @Override
            protected void onSuccess(Boolean result) throws Exception {
                Log.v("onSuccess: ", Thread.currentThread().getName());
                Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                intent.putExtra("user", user);
                startActivity(intent);
            }

            @Override
            protected void onException(Exception e) throws RuntimeException {
                Log.v("onException: ", Thread.currentThread().getName());
                e.printStackTrace();
            }

            @Override
            protected void onFinally() throws RuntimeException {
                Log.v("onFinally: ", Thread.currentThread().getName());
                loginTask = null;
                LoginActivity.this.finish();
            }
        };
        loginTask.execute();
    }
}
